package com.yangrd.airship.sys.web.config;

import cn.dev33.satoken.stp.StpInterface;
import com.yangrd.airship.upms.domain.Role;
import com.yangrd.airship.upms.domain.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yangrd
 * @date 2021/11/25
 * 自定义权限验证接口扩展
 */
@RequiredArgsConstructor

@Component
public class StpInterfaceImpl implements StpInterface {

    private final UserRepository userRepository;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        return userRepository.findById(toIntegerId(loginId)).map(user -> user.getRoles().stream().map(Role::listPermission).flatMap(List::stream).collect(Collectors.toList())).orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return userRepository.findById(toIntegerId(loginId)).map(user -> user.getRoles().stream().map(Role::getAuthority).collect(Collectors.toList())).orElseThrow(() -> new RuntimeException("用户不存在"));
    }

    private Integer toIntegerId(Object loginId) {
        return Integer.valueOf(loginId.toString());
    }

}
